/**
 * @description防抖函数
 * @param fn
 * @param wait
 */
export const debounce = (fn: (...rest: any) => any, wait: number) => {
  let timer: number | any = null
  return function () {
    if (timer != null) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, wait)
  }
}
/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

// 多维扁平化,处理flat在低端手机不兼容
export const flatten = (arr) => {
  return arr.reduce((pre, cur) => {
    return pre.concat(Array.isArray(cur) ? flatten(cur) : cur)
  }, [])
}

export const isFunction = (f) => {
  return Object.prototype.toString.call(f) === '[object Function]'
}

export const h5GoApp = (params = 'abc') => {
  const win = window as any
  if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
    const loadDateTime: any = new Date()
    win.location = 'oudianyun://' + params //schema链接或者universal link
    window.setTimeout(function () {
      //如果没有安装app,便会执行setTimeout跳转下载页
      const timeOutDateTime: any = new Date()
      if (timeOutDateTime - loadDateTime < 5000) {
        // win.location = '...' //ios下载地址
      } else {
        window.close()
      }
    }, 1500)
  } else if (navigator.userAgent.match(/android/i)) {
    try {
      win.location = 'oudianyun://' + params //schema链接或者universal link
      win.setTimeout(function () {
        // win.location = '...' //android下载地址
      }, 1500)
    } catch (e) {}
  }
}

// 在app端获取视频的首帧图片
export const getVideoPoster = (src) => {
  //#ifdef APP-PLUS
  return new Promise((resolve) => {
    const videoframe = (url) => {
      ;(uni.requireNativePlugin('sn-videoframe') as any).getFrame(
        {
          url,
          time: 0, // 默认0
        },
        (e) => {
          resolve(e.imagePath)
        }
      )
    }

    if ((plus as any).os.name === 'iOS') {
      videoframe(src)
    } else {
      uni.downloadFile({
        url: src,
        success: (e) => {
          videoframe(e.tempFilePath)
        },
      })
    }
  })
  //#endif
}

export const getData = (data, name = 'name', value = 'id') =>
  data.map((item) => ({
    ...item,
    text: item[name],
    label: item[name],
    value: +item[value],
  }))

export const getMap = (data) =>
  data.reduce((pre, curr) => {
    pre[curr?.value] = curr.text
    return pre
  }, {})
